<template>
	<div
		class="newaiworkflow"
		id="work-flow-contianer"
		v-loading="aiLoading"
		element-loading-text="加载中"
		element-loading-spinner="el-icon-loading"
		element-loading-background="rgba(255, 255, 255, 0.8)"
	>
		<!-- 头部 -->
		<div class="nav" @click="handleNavClick">
			<div class="nav-left">
				<span>{{ editBusinessName }}</span>
			</div>
			<div class="nav-right" v-if="!detail">
				<el-button class="btn1" @click="triggerFileSelect">
					<img src="@/assets/img/aiworkflowimage/btnicon.png" alt="" />
					导入已有流程
				</el-button>
				<!-- 隐藏的文件输入框 -->
				<input type="file" ref="fileInput" style="display: none" @change="handleFileChange" />
				<span class="save-btn"><el-button class="btn2" @click="setWorkFlow">保存编辑</el-button> <i v-show="errorContents.length !== 0 || !isCompleted" class="submit-error">·</i></span>
				<el-button class="btn2" @click="back">返回</el-button>
				<el-button class="btn2" @click="exportAiWorkflow">导出</el-button>
			</div>
		</div>
		<div class="content">
			<div class="content-header">
				<div @click="globalClick">
					<p :class="isActiveGlobal ? 'blue' : 'white'">
						<img :src="!isActiveGlobal ? globalImages : globalSsucencyImages" />
					</p>
					<span class="text-hover">全局配置</span>
				</div>

				<div @click="businessClick" v-if="!detail">
					<p :class="isActiveBusiness ? 'blue' : 'white'">
						<img :src="!isActiveBusiness ? businessImages : businesSsucencyImages" />
					</p>
					<span class="text-hover">业务模板</span>
				</div>
				<div @click="UploadVideoClick" class="upload-video">
					<p :class="isActiveUpload ? 'blue' : 'white'">
						<img :src="!isActiveUpload ? uploadImages : videouploadSucencyImages" />
					</p>
					<div class="imgQuestion">
						<img :src="questionIcon" alt="" />
						<span class="tips">流程进行至指定模板时播报的画面</span>
					</div>
					<span class="text-hover">上传视频</span>
				</div>
				<div @click="quesitonClick">
					<p :class="isActiveQuestion ? 'blue' : 'white'">
						<img :src="!isActiveQuestion ? questionImages : questionSsucencyImages" />
					</p>
					<span class="text-hover">智能问答</span>
				</div>
			</div>

			<ChooseAiMode :editBusinessId="editBusinessId" v-if="isActiveGlobal" @submit="globalSave" @cancelSubmit="cancelSubmit" @changeMode="changeMode" :resetNode="resetNode" />

			<BpmnWorkflow
				class="tool-btn"
				ref="BpmnWorkflow"
				:isShowPalette="isActiveBusiness"
				:showDetail="detail"
				:uploadConfig="uploadConfig"
				:bpmn="bpmn"
				:screenHeight="screenHeight"
				:editBusinessId="editBusinessId"
			/>
			<AiQuestion
				:showQuesition="isActiveQuestion"
				:pages="intelligentReply.pages"
				@changePageSize="changePageSize"
				@changeCurrentPage="changeCurrentPage"
				@closeQuesiton="closeQuesiton"
				@save="saveAi"
				:screenHeight="screenHeight"
				:showDetail="detail"
				ref="aiQuestionRef"
			/>
			<UploadVideo
				:UploadDialogVisible="isActiveUpload"
				:uploadConfig="uploadConfig"
				:screenHeight="screenHeight"
				:tabName.sync="activeName"
				@close="closeUploadDialogVisible"
				@uploadSuccess="uploadSuccess"
				@changePageSize="changeVideoPageSize"
				@changeCurrentPage="changeVideoPage"
				@delVideo="delVideo"
				@blurDescription="blurDescription"
				:showDetail="detail"
			/>
		</div>
		<div class="submit-info" :class="screenHeight <= 720 ? 'minScreen' : ''" v-show="errorContents.length !== 0">
			<el-card class="box-card">
				<p class="title">
					<span>温馨提示：</span>
					<span class="close" @click="closeInfo">X</span>
				</p>
				<div class="content-box">
					<div class="info-content" v-for="info in errorContents" :key="info.text">
						<p class="text">{{ info.text }}</p>
					</div>
				</div>
			</el-card>
		</div>
	</div>
</template>

<script>
import {
	bindWorkFlowWithBusinessId,
	getBusinessWorkflow,
	saveAiQuestion,
	updateFormDataByAiFlow,
	updateScenIdsByFlow,
	getBizscenariosBindForm,
	importAiBusinessflow,
	exportAiBusinessflow
} from '../../api/api';
import AiQuestion from '../bpmn/components/workflow/AiQuesttion.vue';
import AIWorkflow from '@/modules/workFlow.js';
import BpmnWorkflow from '../bpmn/components/BpmnWorkflow.vue';
import ChooseAiMode from './ChooseAiMode/index.vue';
import { getAllMainNodes, isBlankNode, getTitle, getScanCodeErrorBranches, getVariableList, getAllWorkstepName } from '../bpmn/utility/utility';
import { mapActions, mapMutations, mapState } from 'vuex';
import { getAiQuestion, getAiworkFlowVideoList, uploadVideoByAiworkId, deleteVideoById, updateVideoMessage, bindTestimony, getBusinessScenceName } from '@/api/api.js';
import Draggabilly from 'draggabilly';
import UploadVideo from './NewAiWorkFlow/UploadVideo.vue';
import { getBranchesHasNonInitVariable, validateInvalidVariable } from '../bpmn/utility/validate';

import xmlStr from '@bpmn/mock/diagram.bpmn';
import _ from 'lodash';
import globalImg from '@/assets/img/global.png';
import globalSsucencyImg from '@/assets/img/globalssucency.png';
import businessImg from '@/assets/img/business.png';
import businesSsucencyImg from '@/assets/img/businessucency.png';
import questionImg from '@/assets/img/questionblue.png';
import questionSsucencyImg from '@/assets/img/questionssucency.png';
import uploadImg from '@/assets/img/videoblue.png';
import videouploadSucencyImg from '@/assets/img/videossucency.png';
import grayQuestionImg from '@/assets/img/aiworkflowimage/grayQuestion.png';

export default {
	name: '',
	components: {
		BpmnWorkflow,
		AiQuestion,
		UploadVideo,
		ChooseAiMode
	},
	data() {
		return {
			activeName: 'broadcast',
			businessData: [],
			isActiveGlobal: false,
			isActiveBusiness: false,
			isActiveQuestion: false,
			submitInfo: false,
			isCompleted: false,
			title: '',
			editBusinessName: '',
			editBusinessId: '',
			workflowData: {},
			detail: false, //否是显示详情，输入框不可编辑
			// 全局配置绑定数据
			globalWorkFlow: {
				keyList: [
					{
						label: '是',
						value: 1
					},
					{
						label: '否',
						value: 0
					}
				],
				activeName: 'five',
				nextList: [
					{
						value: 'send-message',
						label: '转人工服务'
					},
					{
						value: 'hangup',
						label: '挂断'
					}
				],
				isRecordStep: 0, // 是否开启视频打点
				exceptionNext: 'hangup', // 机器人异常 默认挂断
				isRealTime: 0, // 是否开启人脸检测
				intervalMS: null, // 人脸时间间隔
				confidence: null, // 阈值
				isFaceLiveRealTime: 0, // 是否开启活体检测
				faceLiveIntervalMS: null, // 活体时间间隔
				faceLiveConfidence: null, // 活体阈值
				formList: [] // 当前业务场景可绑定表单
			},
			bpmn: '',
			// 图片加载不出来，require导入
			globalImages: globalImg,
			globalSsucencyImages: globalSsucencyImg,
			businessImages: businessImg,
			businesSsucencyImages: businesSsucencyImg,
			questionImages: questionImg,
			questionSsucencyImages: questionSsucencyImg,
			errorContents: [],
			nodeBranches: [],
			screenHeight: window.screen.height,
			loginUrl: loginUrl,
			UploadDialogVisible: false,
			uploadImages: uploadImg,
			videouploadSucencyImages: videouploadSucencyImg,
			questionIcon: grayQuestionImg,
			isActiveUpload: false,
			aiLoading: false, // ai工作流 loading 加载中显示隐藏
			variableList: [], // 智能问答变量列表
			showToastQuestion: false // NLU服务挂了，智能问答toast提示
		};
	},

	computed: {
		...mapState({
			userInfo: state => state.login.userInfo,
			urls: state => state.login.urls,
			intelligentReply: state => state.intelligentReply,
			bizflowId: state => state.uploadVideo.bizflowId,
			speakVideoData: state => state.uploadVideo.speakVideoData,
			silentVideoData: state => state.uploadVideo.silentVideoData,
			videoPages: state => state.uploadVideo.pages,
			nonInitVariableList: state => state.associatedVariable.nonInitVariableList,
			invalidVariableList: state => state.associatedVariable.invalidVariableList
		}),
		...mapState('workflow', ['worksteps', 'startNode', 'curShowNode']),
		uploadConfig: {
			// getter
			get: function () {
				const url = `${this.loginUrl}/ivcs/api/v1/upload`;
				const token = localStorage.getItem(`zco_admin_token_${window.uid}`); // this.userInfo.adminToken;
				return {
					url: url,
					headers: { 'x-access-token': token }
				};
			},
			// setter
			set: function () {}
		}
	},
	watch: {
		activeName(newValue) {
			let type = newValue === 'silent' ? 'mute' : 'normal';
			this.initVideoList(type);
		}
	},
	async mounted() {
		// ai工作流 loading 加载中
		this.aiLoading = true;
		// 获取全部智能问答的变量列表
		try {
			await this.getAiQuestionAll();
		} catch (error) {
			console.log(error);
		}
		this.initBindForm();
		this.setViewFlow(false);
		this.detail = this.$route.query.detail === 'true';
		AIWorkflow.setIsDetail(this.detail);
		this.editBusinessName = sessionStorage.getItem('aiBizflowTitle');
		this.editBusinessId = this.$route.query.id;
		AIWorkflow.setBusinessId(this.$route.query.bizscenariosId);
		// console.log(this.$route.params.id, 'ai工作流ID');
		this.setVideoBizflowId(this.editBusinessId);
		this.initVideoList('mute');
		this.initVideoList('normal');
		this.$store.commit('SET_INTELLIGEN_FLOW_ID', this.editBusinessId);
		this.$nextTick(() => {
			let container = document.querySelector('.el-main');
			if (container) {
				container.scrollTop = 0;
			}
		});

		// 全局配置拖拽
		let elem2 = document.getElementById('content-leftFirst');
		if (elem2) {
			// console.log('elem2:', elem2);
			// eslint-disable-next-line no-new
			new Draggabilly(elem2, {
				// options...
				containment: '.canvas'
			});
		}

		/** 屏幕高度大于 720 允许拖拽 */
		if (this.screenHeight > 720) {
			// 智能问答拖拽
			const aiquestion = document.getElementById('ai-question');

			console.log(aiquestion);
			// eslint-disable-next-line no-new
			new Draggabilly(aiquestion, {
				// options...
				containment: '.canvas'
			});
			// 上传视频的拖拽
			const uploadVideo = document.getElementById('upload-video');
			// eslint-disable-next-line no-new
			new Draggabilly(uploadVideo, {
				// options...
				containment: '.canvas'
			});
		}
	},

	methods: {
		...mapActions('workflow', ['addWorkStep', 'setStartNode', 'setWorkSteps', 'updateBreakRuleStatus', 'setBreakRuleNodes', 'setViewFlow', 'resetAllTemplateName', 'resetWorkflowState']),
		...mapMutations('intelligentReply', ['SET_INTELLIGEN_REPLY', 'SET_INTELLIGEN_FLOW_ID', 'SET_INTELLIGEN_PAGES']),
		...mapActions('uploadVideo', ['setVideoBizflowId', 'setVideoPages', 'setSilentVideoData', 'setSpeakVideoData']),
		...mapActions('associatedVariable', ['SET_VARIABLE_LIST']),

		exportAiWorkflow() {
			console.log('exportAiWorkflow');
			let workflowId = this.$route.query.id;
			exportAiBusinessflow(workflowId)
				.then(res => {
					console.log('exportAiBusinessflow res', res);
				})
				.catch(error => {
					console.log('exportAiBusinessflow err', error);
					this.$requestApiError(error, () => {
						this.$router.push('/');
					});
				});
		},

		// 模拟点击隐藏的文件输入框
		triggerFileSelect() {
			this.$refs.fileInput.click();
		},
		// 处理文件选择
		handleFileChange(event) {
			const file = event.target.files[0];
			if (file && file.type === 'application/json') {
				const reader = new FileReader();
				reader.onload = e => {
					try {
						const jsonData = JSON.parse(e.target.result);
						console.log('JSON Data:', jsonData);
						let workflowId = this.$route.query.id;
						importAiBusinessflow(workflowId, jsonData)
							.then(res => {
								console.log('importAiBusinessflow res', res);
								this.$message.success('导入成功');
								window.location.reload();
							})
							.catch(error => {
								console.log('importAiBusinessflow err', error);
								this.$requestApiError(error, () => {
									this.$router.push('/');
								});
							});
					} catch (error) {
						console.error('Error parsing JSON:', error);
						this.$message.error('请上传有效的JSON文件');
					}
				};
				reader.readAsText(file);
			} else {
				this.$message.error('请上传有效的JSON文件');
			}
		},
		init() {
			if (this.workflowData && this.workflowData.workflow && this.workflowData.workflow.talks) {
				const talks = JSON.parse(JSON.stringify(this.workflowData.workflow.talks));
				delete talks.startNode;
				console.log('talks:', talks);
				if (!this.bpmn) {
					// set workflow to store
					this.setWorkSteps(talks);
				}

				// 获取所有节点名称
				let allTemplateName = [];
				for (let key in talks) {
					if (talks[key].name) {
						allTemplateName.push(talks[key].name);
					}
				}
				this.resetAllTemplateName(allTemplateName);
				this.bpmn = this.workflowData.workflow.bpmnXml;
			} else {
				this.bpmn = null;
			}
		},
		// 选择表单数据
		initBindForm() {
			const scenarioId = this.$route.query.bizscenariosId;
			getBizscenariosBindForm(scenarioId)
				.then(res => {
					this.formList = res.data.result || [];
					this.getWorkFlowDetail();
					this.aiLoading = false;
				})
				.catch(() => {
					this.$message.error('获取表单列表失败');
					this.aiLoading = false;
				});
		},
		// 更新ai流程
		uploadWorkflow(workFlow) {
			console.log('getRobotProperty', AIWorkflow, AIWorkflow.getRobotProperty());
			console.log(workFlow.talks);
			let para = {
				talks: workFlow.talks,
				robotProperty: AIWorkflow.getRobotProperty(),
				compareFace: AIWorkflow.compareFace,
				detectLivingFace: AIWorkflow.detectLivingFace,
				exceptionNext: AIWorkflow.exceptionNext,
				serviceException: AIWorkflow.serviceException,
				videoMarks: AIWorkflow.videoMarks,
				variableDict: JSON.parse(localStorage.getItem('variableDict')),
				bpmnXml: workFlow.bpmnXml,
				variables: workFlow.variables,
				materials: workFlow.materials,
				testimonys: workFlow.testimonys
			};
			console.log('update ai workflow', para);
			this.$Spin.show();
			bindWorkFlowWithBusinessId(para, this.editBusinessId, this.isCompleted)
				.then(resp => {
					console.log(resp);
					this.$message.success('保存成功');
					this.getWorkFlowDetail();
					this.$Spin.hide();
				})
				.catch(error => {
					console.log(error);
					this.getWorkFlowDetail();
					this.$Spin.hide();
					let response = error.response;
					this.$requestApiError(response, () => {
						this.$router.push('/');
					});
					if (error.code == '6009') {
						this.$message.error(`业务场景启用中，无法进行操作！`);
						// reload
						setTimeout(() => {
							this.$router.go(0);
						}, 1000);
					}
				});
		},
		// closeBtn() {
		// 	this.isActiveGlobal = !this.isActiveGlobal;
		// },

		async setWorkFlow(workFlow) {
			const now = new Date().getTime();
			console.log('workFlow:', workFlow);
			const self = this;
			self.aiLoading = true;
			const stepsText = JSON.stringify(self.worksteps);
			let worksteps = JSON.parse(stepsText);
			// 获取全部节点
			const steps = getAllWorkstepName(this.worksteps) || [];
			// 筛选有效表单
			const forms = steps.filter(item => item.type === 'sendFormNode' && item.completed) || [];
			let formIds = [];
			forms.map(item => {
				const id = worksteps[item.taskId].after.data.data.data.formId;
				formIds = formIds.concat(id);
			});
			console.log('formIds', formIds);
			// 刷选所有业务场景
			const scenes = steps.filter(item => item.type === 'bizScenTransferNode' && item.completed) || [];
			const scenIds = scenes.map(item => worksteps[item.taskId].do.data.data.data.bizSceneId);
			console.log('scenIds', scenIds);
			// 刷选所有的抄录证言
			const testimonys = steps.filter(item => item.type === 'testimonyWrite' && item.completed) || [];
			const testimonyIds = testimonys.map(item => worksteps[item.taskId].after.data.data.data.testimonyId);
			console.log('testimonyIds', testimonyIds);
			// 获取AI说中的变量 "data": "{{客户ID_1806}}11{{身份证号_1808}}" .match(/\{{([^}]+)\}}/gm)
			const matched = stepsText.match(/\{{([^}]+)\}}/gm) || [];
			let variables = getVariableList(worksteps, self.variableList);
			matched.map(item => {
				const parts = item.split('_');
				if (parts && parts.length >= 2) {
					variables.push(parseInt(parts[parts.length - 1], 10));
				}
			});
			console.log('variables', variables);
			// 业务资料
			const bzmaterias = steps.filter(item => ['sendVideoNode', 'signContract'].includes(item.type) && item.completed) || [];
			const materias = bzmaterias.map(item => worksteps[item.taskId].do.data.data.id);
			console.log('materias', materias);
			// workFlow.talks
			const result = await this.$refs.BpmnWorkflow.bpmnModeler.saveXML({ format: true });
			const { xml } = result;
			if (xml && xml.length > 0) {
				// filter worksteps
				self.$refs.BpmnWorkflow.filterWorkSteps(xml, worksteps)
					.then(steps => {
						console.log(steps);
						worksteps = steps;
						worksteps.startNode = AIWorkflow.startNode;
						workFlow.bpmnXml = xml;
						workFlow.talks = self.validateWorkFlow(steps);
						workFlow.variables = variables;
						workFlow.materials = materias;
						workFlow.testimonys = testimonyIds;
						console.log('materials', workFlow.materials, workFlow.testimonys);
						console.log(workFlow.talks);
						self.uploadWorkflow(workFlow);
						self.updateFormStatus(formIds);

						/** 2021-11-29 注释业务场景校验 */
						// self.updateSceneStatus(scenIds);
						self.aiLoading = false;
						// self.updateBindTestimony(testimonyIds);
						console.log('duration', new Date().getTime() - now);
					})
					.catch(error => {
						console.error('filter work steps error : ', error);
						self.aiLoading = false;
					});
			}
		},

		// 校验 workflow 完整性
		validateWorkFlow(workflow) {
			let info = [];
			let branches = [];
			// 判断是否存在引用非初始化变量的模板其父节点没有对其赋值的模板
			const nonInitVariableList = getBranchesHasNonInitVariable(workflow, AIWorkflow.startNode, this.nonInitVariableList);
			if (nonInitVariableList && nonInitVariableList.length > 0) {
				let self = this;
				// console.warn(workflow.startNode.startsWith('variableCollection'));
				//信息收集不弹toast 提示
				nonInitVariableList.map((item, index) => {
					// console.warn(item, index, 'nonInitVariableList'.workflow.variableCollection);
					setTimeout(() => {
						self.$message.warning(`变量${item.name}未被赋值，请注意！`);
					}, index + 1 * 500);
				});
			}
			let worksteps = _.cloneDeep(workflow);
			worksteps.needHearing = true;
			let nodes = getAllMainNodes(worksteps, AIWorkflow.startNode);
			console.log('getAllMainNodes', nodes, worksteps, AIWorkflow.startNode);
			if (!AIWorkflow.startNode) {
				console.log(AIWorkflow.startNode, 999);
				this.addTips(info, { name: AIWorkflow.startNode, text: 'AI流程开始节点不可成为最后一个节点，请检查后再保存！' });
				this.errorContents = info;
				this.isCompleted = false;
				return worksteps;
			}
			if (isBlankNode(AIWorkflow.startNode)) {
				this.addTips(info, { name: AIWorkflow.startNode, text: '起始节点连接的流程节点中不允许存在空节点，请检查后再保存！' });
				this.isCompleted = false;
				this.errorContents = info;
				return worksteps;
			}
			if (worksteps[AIWorkflow.startNode] && !worksteps[AIWorkflow.startNode].completed) {
				this.addTips(info, { name: worksteps[AIWorkflow.startNode].id, text: `AI流程 <${getTitle(worksteps[AIWorkflow.startNode].id, true)}> 未完成编辑，请检查后再保存！` });
			}
			let allNodes = nodes.map(item => item.split('_')[0]);
			console.log('allNodes:', allNodes);
			if (
				allNodes.indexOf('hangup') === -1 &&
				allNodes.indexOf('transfer') === -1 &&
				allNodes.indexOf('sceneTransfer') === -1 &&
				!AIWorkflow.startNode.includes('transfer') &&
				!AIWorkflow.startNode.includes('hangup') &&
				!AIWorkflow.startNode.includes('sceneTransfer')
			) {
				this.addTips(info, { name: '', text: 'AI流程仅结束模板、转人工模板、场景转接可作为结束节点，请检查后再保存！' });
			}
			nodes.forEach(node => {
				if (isBlankNode(node)) {
					this.addTips(info, { name: worksteps[node].id, text: `AI流程 <${getTitle(worksteps[node].id, true)}> 不能是最后一个节点，请检查后再保存！` });
					let elemnts = document.querySelectorAll('.djs-crosshair');
					elemnts.forEach(ele => {
						ele.style.stroke = 'rgb(246, 163, 161)';
					});
				} else if (worksteps[node] && !worksteps[node].completed && node !== AIWorkflow.startNode) {
					this.addTips(info, { name: worksteps[node].id, text: `AI流程 <${getTitle(worksteps[node].id, true)}> 未完成编辑，请检查后再保存！` });
				}
			});

			// 获取扫码失败和扫码超时的分支
			const scanCodeErrorBranches = getScanCodeErrorBranches(worksteps, AIWorkflow.startNode);

			let scanCodeBreakRule = false;
			// 判断扫码失败和扫码超时的分支中是否含有查阅等待
			let breakRuleNodes = [];
			scanCodeErrorBranches.map(item => {
				const joinItem = item.join(',');
				const indexScanCode = joinItem.indexOf('scanCode');
				const indexMessageSummary = joinItem.indexOf('messageSummary');
				const indexWaitingRead = joinItem.indexOf('waitingRead');

				if (indexScanCode >= 0 && indexWaitingRead > 0 && indexScanCode < indexWaitingRead) {
					item.map(subItem => {
						if (subItem.includes('waitingRead') && worksteps[subItem].fromNode && worksteps[subItem].fromNode.includes('scanCode')) {
							this.addTips(info, { name: subItem, text: `AI流程 <${getTitle(subItem, true)}> 不可存在于扫码失败/扫码超时的流程分支中，请检查后再保存！` });
							worksteps[subItem].breakRule = true;
							this.updateBreakRuleStatus(worksteps[subItem]);
						}
					});
					breakRuleNodes.push(item);
				}
				if (indexWaitingRead >= 0 && indexScanCode < 0 && indexMessageSummary < 0) {
					// 查阅等待<节点ID>所在流程分支中的父节点未找到推送扫码模块，请检查后再保存！
					item.map(subItem => {
						if (subItem.includes('waitingRead')) {
							this.addTips(info, { name: subItem, text: `查阅等待 <${getTitle(subItem, true)}> 所在流程分支中的父节点未找到推送扫码模块/信息汇总模块，请检查后再保存！` });
							worksteps[subItem].breakRule = true;
							this.updateBreakRuleStatus(worksteps[subItem]);
						}
					});
				}
			});
			this.setBreakRuleNodes(breakRuleNodes);
			if (scanCodeBreakRule) {
				console.error('扫码失败或扫码超时的分支中是否含有查阅等待');
			}
			// AI流程<模板名称 节点ID>中关联的变量<变量名>已作废，请检查后在保存！,暂不启用
			// const invalidVariableList = validateInvalidVariable(workflow, AIWorkflow.startNode, this.invalidVariableList);
			// if (invalidVariableList && invalidVariableList.length > 0) {
			// 	invalidVariableList.map(item => {
			// 		this.addTips(info, { name: '', text: `AI流程<${getTitle(item.workstep.id, true)}>中关联的变量<${item.variable.name}>已作废，请检查后在保存！` });
			// 	});
			// }

			this.errorContents = info;
			this.nodeBranches = branches;
			if (this.errorContents.length === 0) {
				this.isCompleted = true;
			} else {
				this.isCompleted = false;
			}
			return worksteps;
		},
		// 添加tips
		addTips(tips, tip) {
			if (!tips || !tip) {
				return;
			}
			let found = false;
			tips.map(item => {
				if (item.text === tip.text) {
					found = true;
				}
			});
			if (!found) {
				tips.push(tip);
			}
		},
		// 点击全局配置 icon
		globalClick() {
			console.log('globalClick', this.isActiveGlobal);
			this.isActiveBusiness = false;
			this.isActiveQuestion = false;
			this.isActiveUpload = false;
			// this.isActiveGlobal = !this.isActiveGlobal;
			// 如果是展开，则点击执行关闭页面操作
			if (this.isActiveGlobal) {
				this.cancelSubmit();
				return;
			}
			// loading new data
			this.getWorkFlowDetail(true);
		},
		// 点击业务模板 icon
		businessClick() {
			// console.log(this.isActiveBusiness, 'isActiveBusiness');
			this.isActiveBusiness = !this.isActiveBusiness;
			let elem = document.querySelector('.djs-palette');
			console.log(elem, 'elem', document.getElementsByClassName('djs-palette'));
			console.log(this.$refs.BpmnWorkflow, 'BpmnWorkflow');
			if (elem) {
				elem.classList.add('drop-menu');
			} else {
				this.$refs.BpmnWorkflow.init();
				this.$refs.BpmnWorkflow.dragPalette();
			}
			this.isActiveGlobal = false;
			this.isActiveQuestion = false;
			this.isActiveUpload = false;
		},
		// 点击智能问答 icon
		quesitonClick() {
			console.log('ttt', this.showToastQuestion);
			if (this.showToastQuestion) {
				this.$message.error('NLU异常，无法查看和编辑！');
				return;
			}
			if (!this.isActiveQuestion) {
				this.initAiQuesttion();
			}
			this.isActiveQuestion = !this.isActiveQuestion;
			this.isActiveGlobal = false;
			this.isActiveBusiness = false;
			this.isActiveUpload = false;
		},
		//上传视频 icon
		async UploadVideoClick() {
			await this.initVideoList('mute');
			await this.initVideoList('normal');
			this.isActiveUpload = !this.isActiveUpload;
			this.isActiveBusiness = false;
			this.isActiveQuestion = false;
			this.isActiveGlobal = false;
		},
		back() {
			this.$router.go(-1);
		},

		// 关闭智能问答
		closeQuesiton() {
			let pages = { page: 1, pageSize: 10, total: 0 };
			this.$store.commit('SET_INTELLIGEN_PAGES', pages);
			this.isActiveQuestion = false;
		},

		// 初始化获取全局配置详情
		getWorkFlowDetail(showView = false) {
			this.$Spin.show();
			let defaultUserKey = [
				{ label: '姓名', value: 'fullName' },
				{ label: '性别', value: 'gender' }
			];

			getBusinessWorkflow(this.editBusinessId)
				.then(resp => {
					console.log('getBusinessWorkflow : ', resp);
					this.$Spin.hide();
					this.workflowData = resp.data;
					this.isCompleted = resp.data.status || false;

					if (resp.data && resp.data.workflow) {
						const { compareFace = {}, detectLivingFace = {}, exceptionNext = null, videoMarks = {}, robotProperty = null, talks = {} } = resp.data.workflow;
						if (!robotProperty) {
							AIWorkflow.setOldVersion(true);
							AIWorkflow.setRobotProperty({ videoType: '', audioType: '', silentVideo: '', talkingVideo: '' });
							this.resetNodeTips();
							return;
						}
						this.init();
						AIWorkflow.setRobotProperty(robotProperty);
						AIWorkflow.setCompareFace(compareFace);
						AIWorkflow.setDetectLivingFace(detectLivingFace);
						AIWorkflow.setExceptionNext(exceptionNext);
						AIWorkflow.setVideoMarks(videoMarks);
						// 非全局配置时在设置startNode
						if (!showView) {
							AIWorkflow.setStartNode(talks?.startNode || null);
						}
						// set start node to store
						this.setStartNode(AIWorkflow.startNode);
						// 人工工作流变量
						if (resp.data.workflow.variableDict) {
							localStorage.setItem('variableDict', JSON.stringify(resp.data.workflow.variableDict));
						} else {
							localStorage.setItem('variableDict', JSON.stringify(defaultUserKey));
						}
					} else {
						localStorage.setItem('variableDict', JSON.stringify(defaultUserKey));
						AIWorkflow.setDefault();
						this.bpmn = null;
					}
					this.workflowData.variableDict = JSON.parse(localStorage.getItem('variableDict'));
					if (showView) {
						this.isActiveGlobal = !this.isActiveGlobal;
					}
				})
				.catch(error => {
					this.$Spin.hide();
					let response = error.response;
					this.$requestApiError(response, () => {
						this.$router.push('/');
					});
					console.log('getBusinessWorkflow error', error);
				});
		},

		resetNodeTips() {
			this.$confirm('AI工作流编辑功能调整，原编辑流程现已不支持，请重新进行编辑！', '温馨提示', {
				confirmButtonText: '确定',
				showClose: false,
				showCancelButton: false,
				type: 'warning'
			})
				.then(() => {
					this.resetNode();
					this.isActiveGlobal = true;
					this.setOldVersion(false);
					this.init();
					this.$message({
						type: 'success',
						message: '重置成功!'
					});
				})
				.catch(e => {
					console.log(e);
					// this.$router.go(-1);
					// this.$message({
					// 	type: 'info',
					// 	message: '已取消'
					// });
				});
		},

		// 全局配置保存
		globalSave(activeName) {
			console.log('globalSave activeName', activeName);
			this.isActiveGlobal = !this.isActiveGlobal;
			let para = {};
			if (activeName !== 'ai-property' && activeName) {
				para = {
					compareFace: AIWorkflow.compareFace,
					detectLivingFace: AIWorkflow.detectLivingFace,
					exceptionNext: AIWorkflow.exceptionNext,
					serviceException: AIWorkflow.serviceException,
					videoMarks: AIWorkflow.videoMarks
				};
			} else {
				para = {
					robotProperty: AIWorkflow.getRobotProperty(),
					compareFace: AIWorkflow.compareFace,
					detectLivingFace: AIWorkflow.detectLivingFace,
					exceptionNext: AIWorkflow.exceptionNext,
					serviceException: AIWorkflow.serviceException,
					videoMarks: AIWorkflow.videoMarks
				};
			}
			console.log('保存全局配置', para);
			this.$Spin.show();
			bindWorkFlowWithBusinessId(para, this.editBusinessId, this.isCompleted)
				.then(resp => {
					console.log(resp);
					this.$Spin.hide();
				})
				.catch(error => {
					console.log(error);
					this.$Spin.hide();
					let response = error.response;
					this.$requestApiError(response, () => {
						this.$router.push('/');
					});
					if (error.code == '6009') {
						this.$message.error(`业务场景启用中，无法进行操作！`);
					}
				});
		},

		cancelSubmit() {
			console.log('workflowData', this.workflowData);
			const { workflow = null } = this.workflowData;
			let robotProperty = { audioType: '', silentVideo: '', talkingVideo: '', videoType: '' };
			console.log(workflow);
			let exceptionNext = 'hangup';
			let detectLivingFace = { confidence: null, intervalMS: null, isRealTime: false, allowablePassRate: 0.3 };
			let compareFace = { confidence: null, intervalMS: null, isRealTime: false, allowablePassRate: 0.3 };
			if (workflow) {
				exceptionNext = workflow.exceptionNext;
				detectLivingFace = workflow.detectLivingFace;
				compareFace = workflow.compareFace;
			}
			if (workflow && workflow.robotProperty) {
				robotProperty = workflow.robotProperty;
			}
			AIWorkflow.setRobotProperty(robotProperty);
			AIWorkflow.setExceptionNext(exceptionNext);
			AIWorkflow.setDetectLivingFace(detectLivingFace);
			AIWorkflow.setCompareFace(compareFace);
			this.isActiveGlobal = false;
		},

		// AI 智能问答保存
		//data 意图点和回复话术
		saveAi(data) {
			console.log(data, '意图点和回复话术');
			saveAiQuestion(this.editBusinessId, data)
				.then(res => {
					if (res.status === 200) {
						this.isActiveQuestion = false;
						this.$message.success('保存成功');
					}
				})
				.catch(err => {
					console.log(err);
					if (err.code == '6009') {
						this.$message.error(`业务场景启用中，无法进行操作！`);
						this.$refs.aiQuestionRef.restore();
					} else {
						this.$message.error('保存失败');
					}
				});
			let pages = { page: 1, pageSize: 10, total: 0 };
			this.$store.commit('SET_INTELLIGEN_PAGES', pages);
			// 获取全部智能问答的变量列表
			this.getAiQuestionAll();
		},

		// AI 意图库查询
		//获取Ai智能问答意图点
		initAiQuesttion() {
			const { pages } = JSON.parse(JSON.stringify(this.intelligentReply));
			let flowId = this.$route.params.id || this.editBusinessId;
			getAiQuestion(flowId, pages.page, pages.pageSize, 'false')
				.then(res => {
					console.log(res.data, 'initAiQuesttion:');
					if (res.status === 200) {
						pages.total = res.data.count;
						let data = res.data.data;
						this.replies = data.map(item => ({ no: item.no, name: item.name, reply: item.reply, isSet: false, variables: item.variables ? item.variables : [] }));
						this.replyData = this.replies;
						this.$store.commit('SET_INTELLIGEN_REPLY', this.replies);
						this.$store.commit('SET_INTELLIGEN_PAGES', pages);
					}
				})
				.catch(err => {
					this.$message.error('获取智能问答数据失败！');
					console.log('initAiQuesttion error', err);
				});
		},

		// 分页查询语料库
		// 数据分页
		changePageSize(val) {
			let pages = JSON.parse(JSON.stringify(this.intelligentReply.pages));
			pages.pageSize = val;
			this.$store.commit('SET_INTELLIGEN_PAGES', pages);
			this.initAiQuesttion();
		},
		changeCurrentPage(val) {
			let pages = JSON.parse(JSON.stringify(this.intelligentReply.pages));
			pages.page = val;
			this.$store.commit('SET_INTELLIGEN_PAGES', pages);
			this.initAiQuesttion();
		},

		// 保存 Ai 工作流之后，更新表单状态
		async updateFormStatus(formIds) {
			let data = {};
			data.id = this.$route.params.id;
			data.formIds = Array.from(new Set(formIds));
			try {
				await updateFormDataByAiFlow(data);
			} catch (e) {
				this.$message.error('保存表单信息失败！');
			}
		},

		// 保存 AI 工作流，更新业务场景状态
		async updateSceneStatus(scenIds) {
			let data = {};
			data.id = this.$route.params.id;
			data.scenIds = Array.from(new Set(scenIds));
			try {
				await updateScenIdsByFlow(data);
			} catch (e) {
				this.$message.error('保存业务场景信息失败！');
			}
		},

		closeInfo() {
			this.errorContents = [];
		},
		// 上传视频相关事件
		closeUploadDialogVisible() {
			this.isActiveUpload = false;
		},

		/** 初始化拉取视频列表 */
		async initVideoList(type) {
			try {
				let data = {
					bizflowId: this.bizflowId,
					type: type,
					page: this.videoPages.page,
					pageSize: this.videoPages.pageSize
				};
				let result = await getAiworkFlowVideoList(data);
				const { total, list } = result.data;
				if (type === 'mute') {
					this.setSilentVideoData(list);
					this.setVideoPages({ ...this.videoPages, total });
					this.aiLoading = false;
				} else {
					this.setSpeakVideoData(list);
					this.setVideoPages({ ...this.videoPages, total });
					this.aiLoading = false;
				}
			} catch (error) {
				this.$message.error('初始化视频列表失败！');
				console.log('init video list error', error);
				this.aiLoading = false;
				this.$requestApiError(error, () => {
					this.$router.push('/');
				});
			}
		},

		/** 上传视频 */
		async uploadSuccess(data) {
			try {
				data.type = this.activeName === 'broadcast' ? 'normal' : 'mute';
				await uploadVideoByAiworkId(this.bizflowId, data);
				await this.initVideoList(data.type);
				this.$message.success('视频上传成功！');
			} catch (error) {
				if (error.code == '6009') {
					this.$message.error(`业务场景启用中，无法进行操作！`);
				} else {
					this.$message.error('视频上传失败！');
				}
				console.log(error);
			}
		},

		/** 删除静默视频 */
		delVideo(data) {
			console.log(data);
			this.$confirm(`确定要删除"${data.fileName}"视频吗?是否继续?`, '温馨提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				left: true
			})
				.then(async () => {
					await deleteVideoById({ bizflowId: this.bizflowId, videoId: data.id });
					this.$message({
						type: 'success',
						message: '删除成功!'
					});
					await this.initVideoList(data.type);
				})
				.catch(e => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
					console.log(e);
				});
		},
		async blurDescription(data) {
			try {
				await updateVideoMessage({ bizflowId: this.bizflowId, videoId: data.id, description: data.description });
				await this.initVideoList(data.type);
			} catch (error) {
				console.log(error);
				this.$message.error('保存字幕失败！');
			}
		},
		/** 视频列表分页 */
		changeVideoPage(page) {
			this.setVideoPages({ ...this.videoPages, page: page });
			let type = this.activeName === 'silent' ? 'mute' : 'normal';
			this.initVideoList(type);
		},

		changeVideoPageSize(pageSize) {
			this.setVideoPages({ ...this.videoPages, pageSize: pageSize });
			let type = this.activeName === 'silent' ? 'mute' : 'normal';
			this.initVideoList(type);
		},
		closeVariableSetting() {
			this.isActiveVariable = false;
		},
		resetNode() {
			let para = {
				robotProperty: AIWorkflow.getRobotProperty(),
				compareFace: AIWorkflow.compareFace,
				detectLivingFace: AIWorkflow.detectLivingFace,
				exceptionNext: AIWorkflow.exceptionNext,
				serviceException: AIWorkflow.serviceException,
				videoMarks: AIWorkflow.videoMarks,
				variableDict: JSON.parse(localStorage.getItem('variableDict')),
				talks: {},
				bpmnXml: xmlStr
			};
			console.log('update ai workflow', para);
			this.$Spin.show();
			bindWorkFlowWithBusinessId(para, this.editBusinessId, false)
				.then(resp => {
					console.log(resp);
					this.getWorkFlowDetail();
					this.$Spin.hide();
				})
				.catch(error => {
					console.log(error);
					this.getWorkFlowDetail();
					this.$Spin.hide();
					let response = error.response;
					this.$requestApiError(response, () => {
						this.$router.push('/');
					});
					if (error.code == '6009') {
						this.$message.error(`业务场景启用中，无法进行操作！`);
					}
				});
			this.resetWorkflowState();
			AIWorkflow.setTalks([]);
			this.errorContents = [];
			this.bpmn = null;
			this.$nextTick(() => {
				this.$refs.BpmnWorkflow.bpmnModeler.clear();
				this.$refs.BpmnWorkflow.createNewDiagram();
				window.aiWorkFlowlId = 1;
			});

			// window.location.reload();
		},
		// 保存AI工作流后，更新绑定的证言状态
		async updateBindTestimony(testimonyIds) {
			let data = {};
			data.id = this.$route.params.id;
			data.testimonyIds = Array.from(new Set(testimonyIds));
			try {
				await bindTestimony(data);
			} catch (error) {
				console.log(error);
			}
		},
		getBusinessScenceName() {
			const scenarioId = this.$route.query.bizscenariosId;
			getBusinessScenceName(scenarioId)
				.then(res => {
					console.log(res.data.name, '业务场景名字');
					sessionStorage.setItem('scenceName', res.data.name);
				})
				.catch(err => {
					console.log(err);
					this.$message.error('获取业务场景名字详情失败！');
					this.$requestApiError(err, () => {
						this.$router.push('/');
					});
				});
		},

		/**
		 * 获取智能问答数据，判断nlu服务是否正常。
		 */
		getAiQuestionAll() {
			this.variableList = [];
			console.log('getAiQuestion params', this.$route.query);
			return new Promise((resolve, reject) => {
				getAiQuestion(this.$route.query.id, 1, 1000, 'true')
					.then(res => {
						localStorage.setItem('nluError', 0);
						if (res.status === 200 && res.data.data) {
							res.data.data.map(data => {
								if (data.reply) {
									// reply: '{{客户ID_1806}}'
									const parts = data.reply.split('_');
									if (parts && parts.length >= 2) {
										this.variableList.push(parseInt(parts[parts.length - 1].replace('}}', ''), 10));
									}
								}
							});
							resolve('ok');
						} else {
							reject('error');
						}
					})
					.catch(err => {
						this.$message.error('获取智能问答数据失败！');
						console.log('get getAiQuestionAll error', err);
						this.showToastQuestion = true; // 获取nlu失败
						localStorage.setItem('nluError', 1);
						reject('error');
					});
			});
		},
		// 点击导航栏，隐藏编辑界面
		handleNavClick() {
			window.store.dispatch('workflow/resetCurShowNode');
		}
	}
};
</script>

<style lang="less" scoped>
.newaiworkflow {
	position: relative;
	// 头部样式
	.nav {
		width: 100%;
		padding: 20px 40px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		.nav-left {
			height: 40px;
			border-bottom: 2px solid #409eff;
			span {
				line-height: 38px;
			}
		}
		.nav-right {
			margin-right: 50px;
			.btn2 {
				color: #fff;
				background: #6384fe;
			}
			.btn1 {
				color: #6384fe;
			}
		}
	}
	.save-btn {
		position: relative;
		.submit-error {
			position: absolute;
			width: 8px;
			height: 8px;
			background-color: red;
			border-radius: 50%;
			top: -4px;
			right: 10px;
		}
	}
	.submit-info {
		position: absolute;
		top: 100px;
		right: 60px;
		z-index: 1100;
		.content-box {
			max-height: 300px;
			overflow-y: auto;
		}
		.title {
			display: flex;
			justify-content: space-between;
			padding: 0 10px 20px 0;
			.close {
				cursor: pointer;
			}
		}
		.text {
			padding: 4px 0;
		}
	}
	.content {
		.content-header {
			position: absolute;
			width: 90px;
			// padding: 20px;
			z-index: 5;
			> div {
				display: flex;
				flex-flow: column;
				align-items: center;
				margin-bottom: 20px;
				position: relative;
				> p {
					width: 32px;
					height: 32px;
					line-height: 30px;
					box-shadow: 0px 0px 9px 0px rgba(0, 0, 0, 0.11);
					border-radius: 50%;
					text-align: center;
				}
				> span {
					display: none;
					padding: 2px 10px;
					background: #010102;
					opacity: 0.67;
					border-radius: 4px;
					font-size: 12px;
					color: #fff;
					margin-top: 6px;
				}

				img {
					width: 16px;
					height: 16px;
					vertical-align: middle;
				}

				div.imgQuestion {
					display: inline-block;
					position: absolute;
					left: 60px;
					top: -6px;
					cursor: pointer;
					img {
						width: 12px;
						height: 12px;
					}
					span.tips {
						display: none;
					}
					&:hover {
						span.tips {
							display: block;
							position: absolute;
							background: #f6f6f6;
							min-width: 240px;
							border: 1px solid #ebeef5;
							padding: 10px;
							z-index: 2000;
							color: #333;
							line-height: 1.4;
							text-align: center;
							font-size: 0.21875rem;
							-webkit-box-shadow: 0 0.03125rem 0.1875rem 0 rgb(0 0 0 / 10%);
							box-shadow: 0 0.03125rem 0.1875rem 0 rgb(0 0 0 / 10%);
							word-break: break-all;
						}
					}
				}
				.imgQuestion:hover + span.text-hover {
					display: none;
				}
				&:hover {
					> span.text-hover {
						display: block;
					}
				}
			}
			.blue {
				background-color: #6384fe;
			}
			.white {
				background-color: #fff;
			}
			// div::after {
			// 	content: '';
			// }
			// div:hover {
			// 	> span {
			// 		display: block;
			// 	}
			// }
		}
	}
}
</style>

<style lang="less">
.newaiworkflow {
	.ai-suffix {
		.el-button {
			width: 220px;
			margin: 0 10px;
		}
	}
	.native-container {
		.ai-suffix {
			.el-button {
				width: 220px;
				margin: 0;
			}
		}
	}
	.el-form-item__content {
		display: flex;
		.el-select {
		}
	}
	.el-card__body {
		padding: 10px;
	}
}
</style>
